import time

from utils_lib.encrypt import encrypt_aes, decrypt_aes


# 通用在线传输数据包


class DataBundle(object):

    # 核心：data_content 为 str

    def __init__(self, data_id, data_content, data_source=''):
        self.data_id = data_id
        self.data_source = data_source
        self.data_time = ''
        self.data_describe = ''
        self.data_content = data_content
        self.is_lock = False
        pass

    def set_time(self, _time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())):
        self.data_time = _time

    def set_describe(self, _des=''):
        self.data_describe = _des

    @property
    def data_state(self):
        return self.is_lock

    # 将数据加密 使用对称秘钥
    def encrypt(self, symmetric_key):

        # 当前数据已是加密状态 无需重复加密
        if self.is_lock:
            return 'The data is locked now.'

        # 否则使用AES加密 加密结果为生成16进制字符串
        self.data_content = encrypt_aes(self.data_content, symmetric_key)
        self.is_lock = True
        return

    # 使用对称秘钥解密数据
    def decrypt(self, symmetric_key):

        # 当前数据未加密 无需解密
        if not self.is_lock:
            return 'The data is unlocked now.'

        # 否则解密 AES
        self.data_content = decrypt_aes(self.data_content, symmetric_key)
        self.is_lock = False
        return

    # obj -> dict
    def serialize(self):
        return self.__dict__

    # dict -> obj
    @classmethod
    def deserialize(cls, data_bundle_dict):
        data_id = data_bundle_dict.get('data_id', '')
        data_source = data_bundle_dict.get('data_source', '')
        data_time = data_bundle_dict.get('data_time', '')
        data_describe = data_bundle_dict.get('data_describe', '')
        data_content = data_bundle_dict.get('data_content', '')
        is_lock = data_bundle_dict.get('is_lock', False)

        data_bundle_obj = cls(data_id, data_content, data_source)
        data_bundle_obj.set_time(data_time)
        data_bundle_obj.set_describe(data_describe)
        data_bundle_obj.is_lock = is_lock
        return data_bundle_obj

